package com.newgoldcurrency.activities.main;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.anythink.banner.api.ATBannerListener;
import com.anythink.banner.api.ATBannerView;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.AdError;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.databinding.FragmentInviteBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class InviteFragment extends Fragment {
    private FragmentInviteBinding binding;
    private final List<Call> calls=new ArrayList<>();
    private String shareContent="I'm mining gold on the gold network. Join us quickly. In the future, 1gold is equal to 50usd.My invitation code is:$. Official Website:https://goldrr.com";
    private long mClickTime;
    private MainActivity activity;
    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentInviteBinding.inflate(inflater, container, false);
        activity= (MainActivity) getActivity();
        binding.inviteShare.setOnClickListener(v -> {
            if (checkDoubleClick()){
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_TEXT, shareContent);
                shareIntent.setType("text/plain");
                startActivity(Intent.createChooser(shareIntent, "Share to:"));
            }
        });
        binding.inviteCopy.setOnClickListener(v -> {
            if (checkDoubleClick()){
                ClipboardManager cm = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("Label", binding.inviteCode.getText().toString());
                cm.setPrimaryClip(mClipData);
                Tools.toast("invitation code is copied");
            }
        });
        binding.inviteCode.setText(App.userBean.invitation_code);
        shareContent=shareContent.replace("$",App.userBean.invitation_code);
        initBanner();
        Network.post(new HashMap<>(), "homepage/getShareContent", call -> {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    activity.runOnUiThread(() -> {
                        try {
                            JsonObject jo = JsonParser.parseString(Objects.requireNonNull(response.body()).string()).getAsJsonObject();
                            if (jo.get("message").getAsString().equals("Get share content success")){
                                shareContent = jo.get("data").getAsJsonObject().get("content").getAsString().replace("$", App.userBean.invitation_code+". ");
                            }else{
                                Tools.toast(jo.get("message").getAsString());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    });
                }
            });
            calls.add(call);
        });
        return binding.getRoot();
    }
    private void initBanner() {
        ATBannerView mBannerView = new ATBannerView(activity);
        mBannerView.setPlacementId("b620dbae9744a9");
        int width = Tools.screenWidthPixels(activity);
        int height =  ViewGroup.LayoutParams.WRAP_CONTENT;
        mBannerView.setLayoutParams(new FrameLayout.LayoutParams(width, height));
        mBannerView.setBannerAdListener(new ATBannerListener() {
            @Override
            public void onBannerLoaded() {
                if (binding!=null)binding.inviteBanner.setVisibility(View.VISIBLE);
            }
            @Override
            public void onBannerFailed(AdError adError) {
            }
            @Override
            public void onBannerClicked(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerShow(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerClose(ATAdInfo atAdInfo) {
                if (binding!=null)binding.inviteBanner.setVisibility(View.GONE);
            }
            @Override
            public void onBannerAutoRefreshed(ATAdInfo atAdInfo) {
            }
            @Override
            public void onBannerAutoRefreshFail(AdError adError) {
            }
        });
        binding.inviteBanner.addView(mBannerView);
        if (App.ShowBean.hasBanner){
            mBannerView.loadAd();
//            binding.inviteBanner.setVisibility(View.VISIBLE);
        }else {
            binding.inviteBanner.setVisibility(View.GONE);
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        for (Call c:calls) c.cancel();
    }
}